package Presentacion;

import Clases.Empleado;
import Clases.Vacacion;
import Clases.VacacionId;
import Clases.VacacionPagada;
import Control.ControlEmpleado;
import Control.ControlVacaciones;
import Control.ControlVacacionesPagadas;

import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

public class ManejoVacaciones extends javax.swing.JFrame {

    ControlEmpleado controlE = ControlEmpleado.obtenerInstancia();
    ControlVacaciones controlV = ControlVacaciones.obtenerInstancia();
    ControlVacacionesPagadas controlVP = ControlVacacionesPagadas.obtenerInstancia();

    private ManejoVacaciones() {

        initComponents();
    }
    private static ManejoVacaciones instancia = null;

    public static ManejoVacaciones obtenerInstancia() {
        if (instancia == null) {
            instancia = new ManejoVacaciones();
        }
        return instancia;
    }

    public void init() {
        setTitle(" Manejo de Vacaciones");
        setLocationRelativeTo(null);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        this.setVisible(true);
        jButton3.setEnabled(false);
        jButton4.setEnabled(false);
        jButton5.setEnabled(false);
        limpiarFormulario();
        jTable1.getColumnModel().getColumn(0).setWidth(jTable1.getColumnModel().getColumn(0).getMinWidth() + 10);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(jTable1.getColumnModel().getColumn(0).getMinWidth() + 10);
    }

    public void setCedField(String ceduEmpleado) {

        this.labelCedula.setText(ceduEmpleado);
    }

    public void setCodigo(Long codigo) {
        this.labelCodigo.setText(String.valueOf(codigo));
    }

    public void setLabelNombre(String nombre) {
        this.labelNombre.setText(nombre);
    }

    public void setLabelVacaciones(int vacaciones) {
        this.labelVacaciones.setText(String.valueOf(vacaciones));
    }

    public void llenarTablaVacaciones(int totalVacaciones) {

        String cedulaEmpleado = labelCedula.getText();
        Empleado empleado = controlE.getEmpleadoCedula(Long.valueOf(cedulaEmpleado));
        List<Vacacion> vacaciones = controlV.getVacacionesPorNumEmpleado(empleado.getNumEmpleado());
        List<VacacionPagada> vacacionesP = controlVP.getVacacionesPorNumEmpleado(empleado.getNumEmpleado());
        DefaultTableModel m = (DefaultTableModel) jTable1.getModel();
        m.setRowCount(0);
        if (vacacionesP.isEmpty()) {
            labelVacacionesPagadas.setText("0");
        } else {
            labelVacacionesPagadas.setText(String.valueOf(vacacionesP.size()));
        }
        if (!vacaciones.isEmpty()) {
            try {
                while (m.getRowCount() > 0) {
                    m.removeRow(0);
                }

                for (int i = 0; i < vacaciones.size(); i++) {
                    m.insertRow(m.getRowCount(), new Object[]{new Boolean(false), vacaciones.get(i).getId().getFecha()});
                }

            } catch (Exception e) {
                System.out.println(e.getCause());
                System.out.println(e.getMessage());
            }
        }

        setLabelVacaciones(totalVacaciones);
        jButton3.setEnabled(true);
        jButton4.setEnabled(true);
        jButton5.setEnabled(true);

    }

    public ArrayList<Date> getVacacionesSeleccionadas() {
        ArrayList<Date> vacaciones = new ArrayList<Date>();
        for (int i = 0; i < jTable1.getRowCount(); i++) {
            if ((Boolean) jTable1.getValueAt(i, 0).equals(Boolean.TRUE)) {
                vacaciones.add((Date) jTable1.getValueAt(i, 1));
            }
        }
        return vacaciones;
    }

    void limpiarFormulario() {
        labelNombre.setText("__________________________");
        labelVacaciones.setText("__________________________");
        labelVacacionesPagadas.setText(" _____________ ");
        labelCodigo.setText("__________________________");
        labelCedula.setText("__________________________");
        DefaultTableModel m = (DefaultTableModel) jTable1.getModel();
        try {
            while (m.getRowCount() > 0) {
                m.removeRow(0);
            }
        } catch (Exception e) {
            System.out.println(e.getCause());
        }

    }
    public void setLabelsPagada(String restantes,int pagadas){
    labelVacacionesPagadas.setText(String.valueOf(Integer.valueOf(labelVacacionesPagadas.getText())+pagadas));
    labelVacaciones.setText(restantes);
    
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        labelVacacionesPagadas = new javax.swing.JLabel();
        labelCedula = new javax.swing.JLabel();
        labelVacaciones = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        labelNombre = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        labelCodigo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(710, 400));

        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Gestión de Vacaciones");

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel9.setText("Cédula de empleado: ");

        jButton1.setText("Buscar Empleado");
        jButton1.setToolTipText("Busque un empleado para realizar la gestión de vacaciones.");
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Vacaciones restantes:");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "", "Fecha"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText("Salir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Desasignar Vacaciones");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Asignar Vacaciones");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Pagar Vacaciones");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setText("Vacaciones pagadas:");

        labelVacacionesPagadas.setText("_________________   ");

        labelCedula.setText("_________________________");

        labelVacaciones.setText("__________________________");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel8.setText("Nombre de empleado: ");

        labelNombre.setText("__________________________");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("Código de empleado:");

        labelCodigo.setText("__________________________");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel5))
                                .addGap(23, 23, 23))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(18, 18, 18)))
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(labelNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(labelCodigo, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelVacaciones, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel4)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGap(32, 32, 32)
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(labelVacacionesPagadas))))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGap(175, 175, 175)
                                .addComponent(jLabel1))
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addGap(27, 27, 27)
                                .addComponent(labelCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton5)
                                .addGap(18, 18, 18)
                                .addComponent(jButton2)))
                        .addGap(24, 24, 24))))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 29, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel9)
                                .addComponent(labelCedula)))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelCodigo)
                            .addComponent(jLabel5)))
                    .addComponent(jLabel3))
                .addGap(18, 29, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(labelNombre))
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jLabel4)
                        .addComponent(labelVacacionesPagadas))
                    .addComponent(labelVacaciones))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton3)
                    .addComponent(jButton2)
                    .addComponent(jButton5))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 636, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        ManejoVacacionesPagadas nuevaVacacion = ManejoVacacionesPagadas.obtenerInstancia();
        if (Character.isDigit(labelCedula.getText().charAt(0)) == false) {
            JOptionPane.showMessageDialog(null, "Por favor buscar un empleado primero", "Mensaje", JOptionPane.ERROR_MESSAGE);
        } else {
            nuevaVacacion.init(this.labelCedula.getText(), this.labelNombre.getText());
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        AsignarVacaciones nuevaVacacion = AsignarVacaciones.obtenerInstancia();
        if (Character.isDigit(labelCedula.getText().charAt(0)) == false) {
            JOptionPane.showMessageDialog(null, "Por favor buscar un empleado primero", "Mensaje", JOptionPane.ERROR_MESSAGE);
        } else {
            nuevaVacacion.init(this.labelCedula.getText(), this.labelNombre.getText());
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ArrayList<Date> seleccionados = this.getVacacionesSeleccionadas();
        ArrayList<Date> errores = new ArrayList<Date>();
        Empleado empleado = controlE.getEmpleadoCedula(Long.valueOf(labelCedula.getText()));
        if (seleccionados.size() > 0) {
            int confirmado = JOptionPane.showConfirmDialog(null, "¿Está seguro que quiere eliminar la/las vacaciones seleccionadas?");
            if (JOptionPane.OK_OPTION == confirmado) {
                for (int i = 0; i < seleccionados.size(); i++) {
                    VacacionId id = new VacacionId(seleccionados.get(i), empleado.getNumEmpleado());
                    Date fechaVacacion=id.getFecha();
                    Date hoy=new Date();
                    if(hoy.compareTo(fechaVacacion)<=0){
                    if (!controlV.eliminar(new Vacacion(id, empleado))) {
                        errores.add(seleccionados.get(i));
                    }
                    }else errores.add(seleccionados.get(i));
                    
                }
                if (errores.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "Eliminación exitosa", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                    llenarTablaVacaciones(Integer.parseInt(labelVacaciones.getText()) + 1);

                } else {
                    String s = "No se completo la eliminación para: ";
                    int i = 0;
                    for (i = 0; i < errores.size() - 1; i++) {
                        s += errores.get(i) + ",";
                    }
                    s += errores.get(i);
                    JOptionPane.showMessageDialog(null, s, "Mensaje", JOptionPane.ERROR_MESSAGE);
                }

            }
        } else {
            JOptionPane.showMessageDialog(null, "No se selecciono ninguna vacación para eliminar.", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        limpiarFormulario();
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Empleados empleado = new Empleados();
        empleado.init("consultarVacacion");

    }//GEN-LAST:event_jButton1ActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ManejoVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ManejoVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ManejoVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ManejoVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ManejoVacaciones().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel labelCedula;
    private javax.swing.JLabel labelCodigo;
    private javax.swing.JLabel labelNombre;
    private javax.swing.JLabel labelVacaciones;
    private javax.swing.JLabel labelVacacionesPagadas;
    // End of variables declaration//GEN-END:variables
}
